import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
public class Test {
    public static void main(String[] args) {
        System.out.println("Hello Test");
        Test test = new Test();
        String filePath = "src\\main\\java\\class.xml";
        test.domParse(filePath);
    }
    //使用dom 解析xml文件
    public void domParse(String filePath) {
        //1.创建解析类工厂的对象
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        try {
            //2.通过工厂创建解析类对象
            DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
            //3.解析xml文件
            Document document = documentBuilder.parse(filePath);
            //4.获取根元素
            Element root = document.getDocumentElement();
            System.out.println("root:" + root);
            NodeList childNodes = root.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                //获取当前处理的子节点
                Node node = childNodes.item(i);
                //判断节点的类型，是文本节点还是元素节
                switch (node.getNodeType()) {
                    case Node.TEXT_NODE:
                        System.out.println("文本节点内容：" + node.getTextContent());
                        break;
                    case Node.ELEMENT_NODE:
                        System.out.println("元素节点名字: " + node.getNodeName());
                        //获取当前元素节点中的所有属性
                        NamedNodeMap attributes = node.getAttributes();
                        //循环变量拿到每一个属性
                        for (int j = 0; j < attributes.getLength(); j++) {
                            //强制转换为Attr类型的对象，表示属性
                            Attr attr = (Attr) attributes.item(j);
                            //可以通过方法获取到属性名和属性值
                            System.out.println(attr.getName() + " = " + attr.getValue());
                        }
                        //获取当前节点下面的子节点
                        NodeList nodeList = node.getChildNodes();
                        for (int k = 0; k < nodeList.getLength(); k++) {
                            Node item = nodeList.item(k);
                            //如果这个节点是元素节点的话
                            if (item.getNodeType() == Node.ELEMENT_NODE) {
                                //拿出元素节点的名字和它的文本值
                                System.out.println(item.getNodeName() + " = " + item.getTextContent());
                            }
                        }
                        break;
                    default: throw new RuntimeException("解析到意外的节点类型:"+node);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
